package com.dpwgc.provider.service;

import com.alibaba.fastjson.JSON;
import com.dpwgc.provider.mapper.UserMapper;
import com.dpwgc.provider.model.User;
import com.dpwgc.provider.utils.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.UUID;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    HttpUtil httpUtil;
    @Autowired
    DateUtil dateUtil;
    @Value("${wx.appId}")
    private String appID;
    @Value("${wx.appSecret}")
    private String appSecret;
    @Autowired
    private RestTemplate restTemplate;


    /**
     * 通过UserOpenid查询用户信息，如果用户存在则生成token并缓存至redis
     * @param UserOpenid
     * @return
     */
    public ResultUtil<User> queryUserByOpenidService(String UserOpenid){
        ResultUtil<User> resultUtil = new ResultUtil<>();

        /* 判断参数是否正确 */


        /* 查询用户数据 */
        User user = userMapper.queryUserByOpenid(UserOpenid);


        /* 用户不存在 */
        if (user==null){
            resultUtil.setCode(100);
            resultUtil.setMsg("该用户尚未注册");
            return resultUtil;
        }

        /* 生成token,并将token存储于redis中，设置7200s过期时间 */
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisUtil.set(user.getUserUuid(), token,7200);

        resultUtil.setCode(200);
        resultUtil.setData(user);
        resultUtil.setMsg("用户信息获取成功,token:"+token);
        return resultUtil;
    }

    /**
     * 获取用户openid
     * @param code
     * @return
     * @throws JsonProcessingException
     */
    public ResultUtil<Object> getUserOpenidService(String code) throws JsonProcessingException {
        ResultUtil<Object> result = new ResultUtil<>();
        String res = "";
        try{
            res = httpUtil.doGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + this.appID + "&secret="
                            + this.appSecret + "&js_code="
                            + code
                            + "&grant_type=authorization_code", null);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,String> resJson = JsonReadUtil.getMap(res);


        if (resJson.get("errcode")!=null){
            result.setCode(100);
            result.setMsg(resJson.get("errmsg"));
            return result;
        }

        result.setCode(200);
        result.setData(resJson);
        return result;
    }

    /**
     * 手机号+密码登录
     *
     * @param phoneNum 用户手机号码
     * @param password 用户密码
     * @return ResultUtil<Object>
     */
    public ResultUtil<Object> phoneNumLoginService(String phoneNum,String password){
        ResultUtil<Object> resultUtil = new ResultUtil<>();

        //安全加密类
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        if(password.length()<6 || password.length()>20){

            resultUtil.setCode(100);
            resultUtil.setMsg("密码格式违规");
            return resultUtil;
        }

        User user = userMapper.phoneNumLogin(phoneNum);

        //手机号不存在
        if(user == null){

            resultUtil.setCode(100);
            resultUtil.setMsg("该手机号未注册");
            return resultUtil;
        }
        else {
            //密码解密，匹配
            if(encoder.matches(password,user.getPassword())){

                /* 生成token,并将token存储于redis中，设置7200s过期时间 */
                String token = UUID.randomUUID().toString().replaceAll("-", "");
                redisUtil.set(user.getUserUuid()+"", token,7200);

                resultUtil.setCode(200);
                resultUtil.setMsg("登录成功|token:"+token);
                resultUtil.setData(user);
                return resultUtil;
            }
            else {
                resultUtil.setCode(100);
                resultUtil.setMsg("登录失败");
                return resultUtil;
            }
        }
    }

    /**
     * 插入用户
     * @param user
     * @return
     */
    public ResultUtil<Object> insertUserService(User user){
        ResultUtil<Object> result = new ResultUtil<>();

        user.setCreateTime(dateUtil.getDateTime());
        user.setLastEditTime(dateUtil.getDateTime());
        user.setAdmin(0);
        user.setUserUuid(UUID.randomUUID().toString().replaceAll("-", ""));

        try {
            int col = userMapper.insertUser(user);
            if (col<=0){
                result.setCode(100);
                result.setMsg("用户注册失败");
                return result;
            }
        }catch (Exception e){
            result.setCode(101);
            result.setMsg(e.toString());
            return result;
        }


        /* 生成token,并将token存储于redis中，设置7200s过期时间 */
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisUtil.set(user.getUserUuid(), token,7200);

        Map map = JSON.parseObject(JSON.toJSONString(user), Map.class);

        result.setCode(200);
        result.setData(map);
        result.setMsg("用户注册成功,token:"+token);
        return result;
    }

    /**
     * 更新用户数据
     * @param user
     * @return
     */
    public ResultUtil<Object> updateUserInfoByUserUuidService(User user){


        ResultUtil<Object> result = new ResultUtil<>();

        user.setLastEditTime(dateUtil.getDateTime());
        user.setAdmin(0);

        int col = userMapper.updateUser(user);

        if (col<=0){
            result.setCode(100);
            result.setMsg("更新用户数据失败");
            return result;
        }

        result.setCode(200);
        result.setMsg("更新用户数据成功");
        return result;
    }

    /**
     * 获取用户信息
     * @param userUuid
     * @return
     */
    public ResultUtil<Object> queryUserByUuidService(String userUuid){
        ResultUtil<Object> resultUtil = new ResultUtil<>();

       try{
           User user = userMapper.queryUserByUuid(userUuid);
           if (user == null){

               resultUtil.setCode(100);
               resultUtil.setMsg("暂无该用户信息");
               return resultUtil;
           }
           resultUtil.setCode(200);
           resultUtil.setMsg("获取用户信息成功");
           resultUtil.setData(user);
           return resultUtil;
       }catch (Exception e){
           resultUtil.setCode(100);
           resultUtil.setMsg("获取用户信息失败");
           return resultUtil;
       }
    }


}
